from typing import Literal, Optional, Type

from pydantic import BaseModel
from PySide6.QtCore import QEvent, Qt
from PySide6.QtGui import QTextOption
from PySide6.QtWidgets import QComboBox, QStyledItemDelegate, QTextEdit


class DefaultDelegate(QStyledItemDelegate):
    def __init__(
        self,
        model_class: Optional[Type[BaseModel]],
        parent=None,
    ):
        super().__init__(parent)
        self._literal = {}
        if model_class:
            self._literal = {
                name: info.annotation.__args__
                for name, info in model_class.model_fields.items()
                if info.annotation
                and getattr(info.annotation, "__origin__", None) is Literal
            }

    def createEditor(self, parent, option, index):
        """根据字段类型创建不同的编辑器"""
        # 检查是否为下拉列表字段
        field_name = index.model().headerData(
            index.column(), Qt.Orientation.Horizontal, Qt.ItemDataRole.UserRole
        )
        if field_name in self._literal:
            editor = QComboBox(parent)
            editor.addItems(self._literal[field_name])
            editor.setStyleSheet("""
            QComboBox {
                background-color: white;
                color: black;
                border: 1px solid gray;
            }""")
            return editor

        # 检查是否为多行文本字段（您可以根据需要调整条件）
        # 这里假设除了下拉列表外的文本字段都使用多行编辑器
        editor = QTextEdit(parent)
        editor.setWordWrapMode(QTextOption.WrapMode.WrapAtWordBoundaryOrAnywhere)
        editor.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        editor.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
        editor.setStyleSheet("""
            QTextEdit {
                background-color: white;
                color: black;
                border: 1px solid gray;
            }
        """)
        return editor

    def setEditorData(self, editor, index):
        """设置编辑器的数据"""
        if isinstance(editor, QComboBox):
            value = index.model().data(index, Qt.ItemDataRole.EditRole)
            if value in [editor.itemText(i) for i in range(editor.count())]:
                editor.setCurrentText(str(value) if value else "")
        elif isinstance(editor, QTextEdit):
            value = index.model().data(index, Qt.ItemDataRole.EditRole)
            editor.setPlainText(str(value) if value else "")
        else:
            super().setEditorData(editor, index)

    def setModelData(self, editor, model, index):
        """将编辑器数据保存到模型"""
        if isinstance(editor, QComboBox):
            model.setData(index, editor.currentText(), Qt.ItemDataRole.EditRole)
        elif isinstance(editor, QTextEdit):
            model.setData(index, editor.toPlainText(), Qt.ItemDataRole.EditRole)
        else:
            super().setModelData(editor, model, index)

    def updateEditorGeometry(self, editor, option, index):
        """更新编辑器几何位置"""
        editor.setGeometry(option.rect)

    def eventFilter(self, editor, event):
        """处理编辑器事件"""
        if isinstance(editor, QTextEdit) and event.type() == QEvent.Type.KeyPress:
            if event.key() in (Qt.Key.Key_Return, Qt.Key.Key_Enter):
                # Ctrl+Enter换行，Enter确认编辑
                if event.modifiers() & Qt.KeyboardModifier.ControlModifier:
                    editor.insertPlainText("\n")
                    return True
                else:
                    # 确认编辑
                    self.commitData.emit(editor)
                    self.closeEditor.emit(editor)
                    return True
        return super().eventFilter(editor, event)
